package com.phototodata.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 响应解析工具类
 * 解析接口返回的 JSON 响应
 *
 * @author PhotoToData
 */
public class ResponseParser {

    private final ObjectMapper objectMapper;

    public ResponseParser() {
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 解析接口响应 JSON
     * 响应格式：
     * {
     *   "success": true/false,
     *   "code": "状态码",
     *   "message": "提示信息",
     *   "data": [
     *     {
     *       "a0184": "身份证号",
     *       "message": "单条处理提示",
     *       "imageDate": "二进制照片数据（可能为 null/空字符串/有效二进制）"
     *     }
     *   ]
     * }
     *
     * @param responseJson 响应 JSON 字符串
     * @return 解析后的 Map 对象，包含 success、code、message、data 字段
     * @throws Exception 解析异常
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> parseResponse(String responseJson) throws Exception {
        try {
            Map<String, Object> responseMap = objectMapper.readValue(
                    responseJson, Map.class);

            // 提取字段
            Boolean success = (Boolean) responseMap.get("success");
            String code = String.valueOf(responseMap.get("code"));
            String message = (String) responseMap.get("message");
            List<Map<String, Object>> data = (List<Map<String, Object>>) responseMap.get("data");

            // 构建结果 Map
            Map<String, Object> result = new HashMap<>();
            result.put("success", success);
            result.put("code", code);
            result.put("message", message);
            result.put("data", data);

            return result;

        } catch (Exception e) {
            throw new Exception("响应 JSON 解析失败：" + e.getMessage() + 
                    "，响应内容：" + responseJson.substring(0, Math.min(200, responseJson.length())), e);
        }
    }
}

